package com.zx.mobile.service.proxy;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import com.zx.scp.utils.PropertyUtil;

/**
 * 该类 主要意图 对平安传输 加解密
 * 
 * @author jeffery.lu
 * 
 */
public class PASignHelper {

	/**
	 * 对请求参数 签名验证
	 * 
	 * @param obj
	 * @return
	 */
	public static boolean checkRequestSign(Object obj, String sign) {
		boolean signLegal = false;
		// 获取值对
		try {
			Map<String, String> param = BeanUtils.describe(obj);
			String checkSign = getRequestSign(param);
			if (StringUtils.isNotBlank(checkSign) && checkSign.equals(sign)) {
				signLegal = true;
			}
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return signLegal;
	}

	/**
	 * 获取验证签名信息
	 * 
	 * @param parameters
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private static String getRequestSign(Map<String, String> parameters)
			throws UnsupportedEncodingException {
		StringBuffer text = new StringBuffer("");
		List<Map.Entry<String, String>> paramList = new ArrayList<Map.Entry<String, String>>(
				parameters.entrySet());
		Collections.sort(paramList,
				new Comparator<Map.Entry<String, String>>() {
					public int compare(Map.Entry<String, String> o1,
							Map.Entry<String, String> o2) {
						return (o1.getKey()).toString().compareTo(o2.getKey());
					}
				});
		for (int i = 0; i < paramList.size(); i++) {
			Map.Entry<String, String> tmpMap = paramList.get(i);
			if (!("sign".equalsIgnoreCase(tmpMap.getKey()) || "class"
					.equalsIgnoreCase(tmpMap.getKey()))) {
				text.append(tmpMap.getValue());
				if (i >= paramList.size() - 1) {// 最后 拼接 末尾拼接partnerKey值
					text.append(PropertyUtil.getValue("paGamePartnerKey"));
				}
			}
		}
		return DigestUtils.shaHex(text.toString().getBytes("UTF-8"));
	}
}
